﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace com.lover.common
{
    public class HttpUtils
    {
        private static HttpUtils _instance = new HttpUtils();
        public static HttpUtils getInstance() { return _instance; }
        private HttpUtils() { }

        public string doGet(string url)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            HttpWebResponse resp = request.GetResponse() as HttpWebResponse;
            if (resp.StatusCode != HttpStatusCode.OK)
            {
                UiUtils.getInstance().error("请求失败, 请重试或联系管理员, code=" + resp.StatusCode.ToString());
                return null;
            }
            Stream respStream = resp.GetResponseStream();
            StreamReader sr = new StreamReader(respStream);
            string content = sr.ReadToEnd();
            sr.Close();
            respStream.Close();
            return content;
        }

        public string doPost(string url, string data)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            using (Stream stream = request.GetRequestStream())
            {
                byte[] bytes = UTF8Encoding.UTF8.GetBytes(data);
                stream.Write(bytes, 0, bytes.Length);
            }
            HttpWebResponse resp = request.GetResponse() as HttpWebResponse;
            if (resp.StatusCode != HttpStatusCode.OK)
            {
                UiUtils.getInstance().error("请求失败, 请重试或联系管理员, code=" + resp.StatusCode.ToString());
                return null;
            }
            Stream respStream = resp.GetResponseStream();
            StreamReader sr = new StreamReader(respStream);
            string content = sr.ReadToEnd();
            sr.Close();
            respStream.Close();
            return content;
        }
    }
}
